package simonxianyu.demo.shiro.web.ctl;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.SmartView;
import simonxianyu.demo.shiro.util.LocalConst;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *
 * Created by simon on 2017/3/4.
 */
@Controller
public class IndexCtl implements LocalConst {

  @RequestMapping("/")
  public ModelAndView index(HttpServletRequest req) {
    ModelAndView mav = new ModelAndView();
    String userAgent = StringUtils.lowerCase(req.getHeader("User-Agent"));
    if (StringUtils.contains(userAgent, "idea")) {
      mav.setView(new SmartView() {
        @Override
        public boolean isRedirectView() {
          return false;
        }

        @Override
        public String getContentType() {
          return "text/text";
        }

        @Override
        public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
          response.getWriter().print("ok");
        }
      });
      return mav;
    }
    Subject subject = SecurityUtils.getSubject();
    if (subject.isAuthenticated()) {
      mav.setViewName("dashboard");
    } else {
      mav.setView(REDIRECT_LOGIN_VIEW);
    }
    return mav;
  }

  @RequestMapping("/loginform")
  public ModelAndView loginform() {
    return new ModelAndView();
  }

}
